<template>
  <div class="box">
    <div class="mb50">
      <van-cell-group>
        <van-field
          required
          clearable
          type="password"
          label="旧密码"
          @change="oldChange"
          placeholder="请输入旧密码"
        />

        <van-field
          type="password"
          label="新密码"
          placeholder="请输入新密码"
          @change="newChange"
          @input='newInput'
          :error-message="errorMessage0"
          required
          clearable
          border="false"
        />
        <van-field
          type="password"
          label="重复新密码"
          clearable
          @change="repeatPassword"
          @input='repeatInput'
          placeholder="请重复输入新密码"
          :error-message="errorMessage1"
          required
          border="false"
        />
      </van-cell-group>
    </div>
    <div class="tc"><button class="mainBgColor submit fs30" @click="submit">确认提交</button></div>
  </div>
</template>

<script>
import { updatePassword } from '@/api'
export default {
  components: {
  },

  data () {
    return {
      form: {
        oldPassword: '',
        newPassword: '',
        repeatPassword: ''
      },
      errorMessage0: '',
      errorMessage1: ''
    }
  },
  methods: {
    newInput () {
      this.errorMessage0 = ''
    },
    repeatInput () {
      this.errorMessage1 = ''
    },
    oldChange (e) {
      this.form.oldPassword = e.mp.detail
    },
    newChange (e) {
      this.form.newPassword = e.mp.detail
    },
    repeatPassword (e) {
      this.form.repeatPassword = e.mp.detail
    },
    async submit () {
      if (this.form.oldPassword.length === 0 || this.form.newPassword.length === 0 || this.form.repeatPassword.length === 0) {
        wx.showToast({
          title: '请输入必填项',
          icon: 'none',
          duration: 1000
        })
      } else {
        if (!(/^[a-zA-Z0-9_]{6,18}$/.test(this.form.newPassword))) {
          this.errorMessage0 = '只能输入英文或数字,不可以含空格,至少6位,最多18位'
        } else {
          this.errorMessage0 = ''
          if (this.form.newPassword !== this.form.repeatPassword) {
            this.errorMessage1 = '两次输入不一样'
          } else {
            this.errorMessage1 = ''
            let result = await updatePassword(this.form)
            if (result.data === 'ok') {
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 1000
              })
              setTimeout(function () {
                wx.navigateBack()
              }, 1000)
            } else if (result.data === 1000) {
              wx.showToast({
                title: '密码输入错误',
                icon: 'none',
                duration: 1000
              })
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>
  .mb50{margin-bottom: 50rpx;}
  .box{padding: 20rpx;}
  .submit{color: #fff}
</style>
